import { config } from "./config";
import axios from "axios";
import storage from "../utils/storage";

class VAxios {
  constructor(config) {
    this.axiosInstance = axios.create(config);
    this.setupInterceptor();
  }

  setupInterceptor() {
    this.axiosInstance.interceptors.request.use(
      (config) => {
        // this.transform()
        const ACCESS_TOKEN = storage.get("access_token");
        if (ACCESS_TOKEN) {
          config["headers"]["token"] = ACCESS_TOKEN;
        }
        if (!config["headers"]["Content-Type"]) {
          config["headers"]["Content-Type"] =
            "multipart/form-data; charset=UTF-8";
        }

        return config;
      },
      (err) => {
        return Promise.reject(err);
      }
    );

    this.axiosInstance.interceptors.response.use(
      (res) => {
        switch (res.data.code) {
          case 200 || 0:
            return Promise.resolve(res);
            break;
          case 403:
            ElMessage({
              message: "禁止访问",
              type: "error",
            });
            // router.replace('/403')
            break;
          case 404:
            ElMessage({
              message: "资源未找到",
              type: "error",
            });
            // router.replace('/404')
            break;
          case 500:
            ElMessage({
              message: "服务器出错",
              type: "error",
            });
            // router.replace('/500')
            break;
        }
        return Promise.resolve(res);
      },
      (err) => {
        return Promise.reject(err);
      }
    );
  }

  request(config) {
    return new Promise((resolve, reject) => {
      this.axiosInstance
        .request(config)
        .then((res) => {
          const iscancel = axios.isCancel(res);
          // 请求不被取消
          if (!iscancel) {
            resolve(res);
            return;
          }
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  get(config) {
    return this.request({ ...config, method: "GET" });
  }
  post(config) {
    return this.request({ ...config, method: "POST" });
  }
  delete(config) {
    return this.request({ ...config, method: "DELETE" });
  }
  patch(config) {
    return this.request({ ...config, method: "PATCH" });
  }
}

const http2 = new VAxios(config);
export default http2;
